package com.define.ssh.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.define.ssh.util.SystemUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/* session过期、登录有效性及操作的权限验证拦截器 */
@SuppressWarnings("serial")
public class LoginedCheckInterceptor extends AbstractInterceptor {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Log LOG = LogFactory
			.getLog(LoginedCheckInterceptor.class);

	/** 拦截请求并进行登录有效性验证 */
	@Override
	public String intercept(ActionInvocation ai) throws Exception {
		final HttpServletRequest request = ServletActionContext.getRequest();
		// 取得请求的URL
		final String url = request.getRequestURL().toString();
		final HttpServletResponse response = ServletActionContext.getResponse();
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);
		// 对登录与注销请求直接放行,不予拦截
		if (url.indexOf("logout!logout.xhtml") != -1
				|| url.indexOf("login!checkLogin.xhtml") != -1) {
			return ai.invoke();
		} else {
			// 验证Session是否过期
			if (!ServletActionContext.getRequest().isRequestedSessionIdValid()) {
				// session过期,转向session过期提示页,最终跳转至登录页面
				LOG.info("会话过期:" + getIpAddr(request) + ">" + url);
				return "login";
			} else {
				final String userId = (String) ServletActionContext
						.getRequest().getSession()
						.getAttribute(SystemUtil.USERLOGIN);
				// 验证是否已经登录
				if (userId == null) {
					// 尚未登录,跳转至登录页面
					LOG.info("尚未登录:" + getIpAddr(request) + ">" + url);
					return "login";
				} else {
					LOG.info("正常:" + getIpAddr(request) + ">" + url);
					return ai.invoke();
				}
			}
		}
	}

	/**
	 * 获取访问的ip,这是有nginx的原因
	 * 
	 * @param request
	 * @return
	 */
	private String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}